/**
 * fileName: YLES_SEARCH_TOOL
 * @NApiVersion 2.1
 */

import {EntryPoints} from 'N/types'
import search = require('N/search')
import log = require("N/log");
import record = require("N/record");
import {accMul, percentToString, stringToDate} from "./YLES_Tool";
import {CustomRecordType} from "./YLES_RELATED_RECORDTYPE";

//search处理的回调函数类型
type searchCallBack = (res: search.Result, columns: (search.Column | string)[], obj: object) => void

//签名索引
export interface ObjectJson {
    [prop: string]: string | number | Date | null | boolean
}

//Search返回的基本数据结构
interface BasicRtn {
    detail: ObjectJson[],
    counts: number
}

//处理Search所有数据
export function dealSearch(Search: search.Search, cb: searchCallBack, obj: object) {
    const myPagedData = Search.runPaged({pageSize: 1000});
    myPagedData.pageRanges.forEach(function (pageRange) {
        const myPage = myPagedData.fetch({index: pageRange.index});
        myPage.data.forEach(function (result) {
            cb(result, Search.columns, obj);
        });
    });
}

//处理Search数据。返回指定页数数据
export function dealPageSearch<T extends BasicRtn>(Search: search.Search, cb: searchCallBack, page: number, pageSize: number, obj: T) {
    const myPagedData = Search.runPaged({pageSize: pageSize});
    obj.counts = myPagedData.count;
    if (obj.counts > 0) {
        const PageDate = myPagedData.fetch({index: page}).data;
        PageDate.forEach(function (result) {
            cb(result, Search.columns, obj);
        });
    }
}

//获取所有货品主数据
export function getAllItem() {
    const rtn: { itemInfo: string[] } = {
        "itemInfo": []
    };
    const Search = search.create({
        type: 'item',
        filters: [
            ['isinactive', 'is', 'F']
        ],
        columns: [
            {name: 'itemid'}
        ]
    });

    let cb = (res: search.Result, columns: (search.Column | string)[], obj: any) => {
        obj.itemInfo.push(res.getValue(columns[0]));
    }
    dealSearch(Search, cb, rtn);
    return rtn.itemInfo;
}

//获取存储CSV的顶层文件夹ID
export function getCsvParentFolder() {
    const filters = [];
    const columns = [];
    filters.push(['name','is', 'yles_csv_folder']);
    columns.push(search.createColumn({name: 'internalid'}));

    const thisSearch = search.create({type: 'folder', filters: filters, columns: columns});
    const thisResult = thisSearch.run().getRange({start: 0, end: 1});
    if(thisResult.length > 0){
        return thisResult[0].getValue(columns[0]) as string;
    }
    throw 'Please contact the administrator to create the report storage folder first.';
}

//获取指定名称的文件夹ID
export function getCsvFolder() {
    const now = new Date();
    const folderName = 'ibCsv_' + now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
    //1.获取parent folder
    const pFolderId = getCsvParentFolder();

    //2.获取指定名称且在CSV父级目录下的文件夹，若不存在则新建
    const filters = [];
    var columns = [];
    filters.push(['name','is', folderName]);
    filters.push('and');
    filters.push(['parent','is', pFolderId]);
    columns.push(search.createColumn({name: 'internalid'}));

    var thisSearch = search.create({type: 'folder', filters: filters, columns: columns});
    var thisResult = thisSearch.run().getRange({start: 0, end: 10});
    if (thisResult && thisResult.length > 0) {
        return thisResult[0].getValue(columns[0]) as string;
    }else {
        try{
            //若不存在，则新建
            const folderRecord = record.create({type:'folder'});
            folderRecord.setValue('name', folderName);
            folderRecord.setValue('parent', pFolderId);
            return folderRecord.save();
        }catch (e) {
            log.error({title:'创建文件夹失败',details:e});
        }
    }
    return '';
}